<template>
  <div class="message-send-page">
    <div class="cancel-box">
        <el-button type="success" @click="gotoMessageBOx">返回</el-button>
    </div>

    <!-- 学生列表部分 -->
    <div class="student-search-box">
      <el-text>选择收信人</el-text>
      
        <div class="search-box">
          <el-input v-model="studentName" placeholder="搜索学生姓名" clearable />/
          <el-input v-model="studentEmail" placeholder="搜索学生邮箱" clearable />
          <el-button type="primary" @click="searchStudents">搜索</el-button>
        </div>

        <el-table
          v-if="students.length"
          :data="students"
          stripe
          border
          max-height="80%"
          style="width: 100%;"
          @selection-change="handleSelectionChange"
          >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="username" label="用户名" />
          <el-table-column prop="email" label="邮箱" />
        </el-table>

        <div class="pagination-box">
          <el-pagination
            v-model:current-page="pageNum"
            :page-size="pageSize"
            :total="totalStudents"
            @current-change="fetchStudents"
            layout="total, prev, pager, next, jumper"
          />
        </div>

        <div class="receivers">
        <label>收信人：</label>
        <el-input v-model="selectedStudentsNames" readonly placeholder="选择收件人"/>
      </div>
    </div>

    <!-- 写信部分 -->
    <div class="message-compose-box">
      <el-form ref="form" label-width="100px">
        <el-form-item label="标题">
          <el-input v-model="title" placeholder="请输入信件标题" />
        </el-form-item>

        <el-form-item label="内容">
          <el-input 
            :autosize="{ minRows: 3, maxRows: 8 }" 
            type="textarea" 
            v-model="content" 
            placeholder="请输入信件内容" />
        </el-form-item>

        <el-button type="primary" @click="sendMessage">发送</el-button>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useCookies } from 'vue3-cookies'
import axios from 'axios'
import router from '@/router'

const { cookies } = useCookies()

// 状态管理
const pageNum = ref(1)  // 当前页码
const pageSize = ref(10)  // 每页显示条数
const totalStudents = ref(0)  // 总学生数
const students = ref([])  // 学生列表
const selectedStudents = ref([])  // 被勾选的学生
const selectedStudentsNames = ref('')  // 被选中学生的姓名列表
const title = ref('')
const content = ref('')

const studentName = ref('')
const studentEmail = ref('')

// 获取课程信息
const courseID = cookies.get('selectedCourse')?.id

// 获取课程成员列表
async function fetchStudents() {
    if(!cookies.isKey("selectedCourse"))
        return
  try {
    const res = await axios.get('/api/course/members', {
      params: {
        courseID: courseID,
        pageNum: pageNum.value,
        pageSize: pageSize.value
      }
    })
    if (res.data.code === 200) {
      students.value = res.data.data.records
      totalStudents.value = res.data.data.total
    }
  } catch (error) {
    console.error('获取学生信息失败', error)
    students.value = []
  }
}

// 搜索学生
async function searchStudents() {
  if(studentEmail.value.length > 5){
    try{
        const membersRes = await axios.get(`/api/customer/user/email?email=${studentEmail.value}`)
        if (membersRes.data?.code !== 200) {
            ElMessage({ type: 'error', message: `查询学生失败` });
            throw new Error(membersRes.data.msg || '查询成员失败')
        }
        // 把返回的单条 data 放入数组，以填充表格
        students.value = [membersRes.data.data]
        console.log(membersRes)
    }catch(err){
        ElMessage.error('网络错误，查询失败')
        console.log(err)
    }
  }else if(studentName.value.length > 0){
    try{
        const membersRes = await axios.get(`/api/customer/user/page`, {
            params:{
                pageSize: pageSize.value,
                pageNum: pageNum.value,
                username: studentName.value,
                role: 0,
            }
        })
        if (membersRes.data?.code !== 200) {
            throw new Error(membersRes.data.msg || '查询成员失败')
        }
        if (membersRes.data?.data.records.length <= 0) {
            ElMessage({ type: 'error', message: `不存在课程成员` });
            return
        }
        const list = membersRes.data.data.records
        
        const detailPromises = list.map(async ({ id }) => {
            const userRes = await axios.get(`/api/customer/user/id?id=${id}`)
            if (userRes.data?.code !== 200) {
                console.warn(`获取用户 ${id} 信息失败：`, userRes.data.msg)
                return null
            }  
            const d = userRes.data.data
            // 4. 过滤掉不展示的字段
            return {
                id:         d.id,
                username:   d.username,
                email:      d.email,
                createTime: d.createTime
            }
        })

        // 等待所有完成，并剔除 null
        students.value = (await Promise.all(detailPromises)).filter(x => x)
    } catch (e) {
        console.error(e)
        students.value = []
    }
  }
}

// 选中学生处理
function handleSelectionChange(selection) {
  selectedStudents.value = selection
  selectedStudentsNames.value = selection.map(item => item.username).join(', ')
}

// 发送消息
async function sendMessage() {
  const senderID = cookies.get('cid')
  const receivers = selectedStudents.value.map(item => item.id)

  try {
    const res = await axios.post('/api/notice/add', {
        senderID: senderID,
        receivers: receivers,
        title: title.value,
        content: content.value
    })
    if (res.data.code === 200) {
      alert('消息发送成功')
      selectedStudents.value = []
      selectedStudentsNames.value = ''
    }
  } catch (error) {
    console.error('发送失败', error)
    alert('发送失败')
  }
}

function gotoMessageBOx(){
    router.push({path: '/teacher/messageBox'})
}

// 页面加载时获取学生列表
onMounted(fetchStudents)
</script>

<style scoped>
.cancel-box {
    width: 20%;
    margin-bottom: 30px;
    margin-left: auto; /* 将按钮区域靠右 */
}

.message-send-page {
  width: 80%;
  margin-left: 10%;
  margin-top: 40px;
  background-color: #fbfbfb;
  padding-top: 20px;    /* 顶部内边距20px */
  padding-bottom: 20px; /* 底部内边距20px */
  padding-left: 20px;
  padding-right: 20px;
  border: 1px solid #aaa; /* 1px宽的黑色实线边框 */
  border-radius: 10px; /* 添加圆角效果，10px为圆角半径 */
}

.student-search-box {
  background-color: #eff;
  padding-top: 20px;    /* 顶部内边距20px */
  padding-bottom: 20px; /* 底部内边距20px */
  padding-left: 20px;
  padding-right: 20px;
  border: 1px solid #aaa; /* 1px宽的黑色实线边框 */
  border-radius: 10px; /* 添加圆角效果，10px为圆角半径 */
}

.search-box {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  margin-bottom: 20px;
  gap: 10px; /* 添加gap属性设置控件间距 */
}

.search-box .el-button {
  width: 20%; /* 设置el-button宽度为20% */
}

.search-input {
  width: 45%;
}

.search-button {
  height: 38px;
  margin-left: 10px;
}

.el-table {
  margin-top: 20px;
  width: 100%;
}

.pagination-box {
  margin-top: 20px;
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.message-compose-box {
  margin-top: 30px;
  background-color: #eff;
  padding-top: 20px;    /* 顶部内边距20px */
  padding-bottom: 20px; /* 底部内边距20px */
  padding-left: 20px;
  padding-right: 20px;
  border: 1px solid #aaa; /* 1px宽的黑色实线边框 */
  border-radius: 10px; /* 添加圆角效果，10px为圆角半径 */
}

.receivers {
  width: 80%;
  margin-bottom: 20px;
}

.compose-form {
  max-width: 600px;
  margin: 0 auto;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-button {
  margin-top: 20px;
  width: 100%;
}

.message-content {
  height: 200px;
}
</style>
